import React, { useEffect, useState } from 'react';
import zhCN from 'antd/lib/locale/zh_CN';
import {
  Form,
  Input,
  Button,
  DatePicker,
  Table,
  Space,
  Pagination,
  ConfigProvider,
  message,
  Popconfirm
} from 'antd';
import { getActivityApi, delActivityApi } from '@/api/activity';
import { changeStatus } from '@/utils';
import { history } from 'umi'

const { RangePicker } = DatePicker;

export default function TabShow({keys}) {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [activityName, setActivityName] = useState();
  const [total, setTotal] = useState();
  const [actlists, setActLists] = useState([]);
  const [queryStartDate, setQueryStartDate] = useState();
  const [queryEndDate, setQueryEndDate] = useState();

  /** 请求进行获取数据 */
  const getLists = async (obj) => {
    const res = await getActivityApi(obj);
    setTotal(res.data.data.total);
    const newArr = res.data.data.rows.map((item) => {
      item.key = item.id;
      return item;
    });
    setActLists([...newArr]);
  };

  /** 进入页面进行发请求得到所有的数据 进行渲染 */
  useEffect(() => {
    getLists({ page, pageSize });
  }, []);

  /** 父组件keys值改变 */
   const callback = () => {
     setQueryStartDate('')
     setQueryEndDate('')
     setActivityName('')
     setPage(1)
     setPageSize(5)
     const num = Number(keys)
     if(num === 0) {
       getLists({page, pageSize})
     }else if(num === 7){
       getLists({page: 1, pageSize, isDraft: true})
     }else{
       getLists({page: 1, pageSize, activityStatus: [num]})
     }
   };

   useEffect(() => {
    callback()
   }, [keys])

  /** 时间 */
  const dateChange = (date, dateString) => {
    setQueryStartDate(dateString[0]);
    setQueryEndDate(dateString[1]);
  };

  const [searchForm] = Form.useForm();

  /** 重置 */
  const resetHandler = () => {
    searchForm.resetFields();
    setQueryStartDate('');
    setQueryEndDate('');
    setActivityName('');
  };

  /** 搜索 */
  const searchhandler = () => {
    const { activityName } = searchForm.getFieldsValue();
    if (activityName || queryStartDate) {
      setPage(1);
      setPageSize(5);
      setActivityName(activityName);
      const key = Number(keys);
      if (key === 7) {
        const obj = {
          page: 1,
          pageSize,
          isDraft: true,
          activityName,
          queryStartDate,
          queryEndDate,
        };
        getLists(obj);
      } else if (key === 0) {
        const obj = {
          page: 1,
          pageSize,
          activityName,
          queryStartDate,
          queryEndDate,
        };
        getLists(obj);
      } else {
        const obj = {
          page: 1,
          pageSize,
          activityStatus: [key + ''],
          activityName,
          queryStartDate,
          queryEndDate,
        };
        getLists(obj);
      }
    } else {
      message.error('请输入您要输入的内容');
    }
    searchForm.resetFields();
  };

  /** 分页 */
  const onChangeHandler = (current, pageSize) => {
    setPage(current);
    setPageSize(pageSize);
    const key = Number(keys);
    if (key === 7) {
      const obj = {
        page: current,
        pageSize,
        isDraft: true,
        activityName,
        queryStartDate,
        queryEndDate,
      };
      getLists(obj);
    } else if (key === 0) {
      const obj = {
        page: current,
        pageSize,
        activityName,
        queryStartDate,
        queryEndDate,
      };
      getLists(obj);
    } else {
      const obj = {
        page: current,
        pageSize,
        activityStatus: [key + ''],
        activityName,
        queryStartDate,
        queryEndDate,
      };
      getLists(obj);
    }
  };

  /** 创建活动 */
  const addHandler = () => {
    history.push('/changeAct')
  }

  /** 删除操作  */
  const  confirmHandler = async ({activityBasicId}) => {
    const res = await delActivityApi({activityBasicIds: [activityBasicId]})
    if(res.data.code == 200) {
      message.success('删除成功');
      getLists({
        page,
        pageSize,
        isDraft: true
      })
    }else{
      message.error('删除失败')
    }
  }

  /** 编辑操作 */
  const editHandler = ({activityBasicId}) => {
    history.push({
      pathname: '/changeAct',
      state:{
        activityBasicId
      }
    })
  }
  /** 待审核详情 */
  const auditHanler = ({activityBasicId}) => {
    history.push({
      pathname: '/auditAct',
      state: {
        activityBasicId
      }
    })
  }
  const columns = [
    {
      dataIndex: 'activityName',
      key: 'activityName',
      title: '活动名称',
    },
    {
      dataIndex: 'creator',
      key: 'creator',
      title: '创建人',
    },
    {
      dataIndex: 'gmtCreated',
      key: 'gmtCreated',
      title: '创建时间',
    },
    {
      key: 'gmtModified',
      dataIndex: 'activeTime',
      render: (_, record) => (
        <span key={record.key}>
          {record.startDate} ~ {record.endDate}
        </span>
      ),
      title: '活动时间',
    },
    {
      dataIndex: 'activityStatus',
      key: 'activityStatus',
      title: '状态',
      render: (_, record) => (
        <span key={record.key}>
          {record.isDraft ? '草稿' : changeStatus(record.activityStatus)}
        </span>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => {
          if (record.isDraft) {
            return (
              <Space size="middle">
                <a onClick={() => editHandler(record)}>编辑</a>
                <Popconfirm
                    cancelText="No"
                    okText="Yes"
                    onCancel={() => message.info('已取消')}
                    onConfirm={() => confirmHandler(record)}
                    title="您确定要删除这一条数据么?"
                >
                <a>删除</a>
                </Popconfirm>
              </Space>
            );
          }
          if (changeStatus(record.activityStatus) === '进行中') {
            return (
              <Space size="middle">
                <a>详情</a>
                <a>关闭</a>
              </Space>
            );
          }
          if (changeStatus(record.activityStatus) === '未开始') {
            return (
              <Space size="middle">
                <a>详情</a>
                <Popconfirm
                    cancelText="No"
                    okText="Yes"
                    onCancel={() => message.info('已取消')}
                    onConfirm={() => confirmHandler(record)}
                    title="您确定要删除这一条数据么?"
                >
                <a>删除</a>
                </Popconfirm>
              </Space>
            );
          }
          if (changeStatus(record.activityStatus) === '已结束') {
            return (
              <Space size="middle">
                <a>详情</a>
                <Popconfirm
                    cancelText="No"
                    okText="Yes"
                    onCancel={() => message.info('已取消')}
                    onConfirm={() => confirmHandler(record)}
                    title="您确定要删除这一条数据么?"
                >
                <a>删除</a>
                </Popconfirm>
              </Space>
            );
          }
          if (changeStatus(record.activityStatus) === '待审核') {
            return (
              <Space size="middle">
                <a onClick={() => auditHanler(record)}>详情</a>
              </Space>
            );
          }
          if (changeStatus(record.activityStatus) === '已驳回') {
            return (
              <Space size="middle">
                <a>详情</a>
                <a>重新发布</a>
                <Popconfirm
                    cancelText="No"
                    okText="Yes"
                    onCancel={() => message.info('已取消')}
                    onConfirm={() => confirmHandler(record)}
                    title="您确定要删除这一条数据么?"
                >
                <a>删除</a>
                </Popconfirm>
              </Space>
            );
          }
      }
    }
  ];
  return (
    <div>
      {/** 搜索 */}
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <Form
            form={searchForm}
            labelCol={{ span: 8 }}
            name="search"
            style={{ display: 'flex', width: 800 }}
        >
          <Form.Item label="活动名称"
              name="activityName"
              style={{ flex: 2 }}
          >
            <Input
                onChange={(e) => setActivityName(e.target.value)}
                placeholder="请输入活动名称 模糊搜索"
                value={activityName}
            />
          </Form.Item>
          <Form.Item label="创建时间"
              name="time"
              style={{ flex: 2 }}
          >
            <RangePicker onChange={dateChange} />
          </Form.Item>
        </Form>
        <div>
          <Button
              onClick={searchhandler}
              style={{ borderRadius: 5, marginRight: 10 }}
              type="primary"
          >
            搜索
          </Button>
          <Button onClick={resetHandler}
              style={{ borderRadius: 5 }}
          >
            重置
          </Button>
        </div>
      </div>
      {/** table表格 */}
      <Button onClick={addHandler}
          style={{ borderRadius: 5, marginBottom: 10 }}
          type="primary"
      >
        创建活动
      </Button>
      <Table columns={columns}
          dataSource={actlists}
          pagination={false}
      ></Table>
      {/** 分页 */}
      <div
          style={{
          display: 'flex',
          justifyContent: 'space-between',
          marginTop: 20,
        }}
      >
        <p style={{ lineHeight: '70px', margin: 0 }}>
          共 {total}条数据 第{page} / {Math.ceil(total / pageSize)} 页
        </p>
        <ConfigProvider local={zhCN}>
          <Pagination
              current={page}
              defaultPageSize={pageSize}
              onChange={onChangeHandler}
              pageSizeOptions={[5, 10, 20, 50]}
              showQuickJumper
              showSizeChanger
              style={{ marginTop: 20 }}
              total={total}
          />
        </ConfigProvider>
      </div>
    </div>
  );
}
